package com.frikinet.tools.gui;

import java.awt.Component;

import javax.swing.JMenu;

import com.frikinet.tools.i18n.FI18N;
import com.frikinet.tools.i18n.Translable;

public class FMenu extends JMenu implements Translable, Indexable, IndexContainer
{
	private static final long serialVersionUID = 1L;

	private FI18N i18n = null;
	private String id = "";

	public FI18N getI18n()
	{
		return i18n;
	}

	public void setI18N(FI18N i18n)
	{
		this.i18n = i18n;
	}
	
	public void translate()
	{
		String text = getName();
		if(i18n != null)
			super.setText(parseName(i18n.translate(text)));
		else
			super.setText(parseName(text));
		for(Component c: getMenuComponents())
		{
			if(c instanceof Translable)
				((Translable)c).translate();
		}
	}
	
	public void setId(String id)
	{
		this.id = id;
	}

	public String getId()
	{
		return id;
	}

	public Component findById(String id)
	{
		for(Component c: getMenuComponents())
		{
			if(c instanceof Indexable)
			{
				if(id.equals(((Indexable)c).getId()))
					return c;
			}
			else if(c instanceof IndexContainer)
				return ((IndexContainer)c).findById(id);
		}
		return null;
	}

	private String parseName(String text)
	{
		String stripString = text.replaceAll("_", "");
		int index = text.indexOf('_');
		if(index >= 0)
			setMnemonic(text.charAt(index+1));
		return stripString;
	}
}
